package com.thinkit.bigdata.web.controller;

import com.alibaba.fastjson.JSON;
import com.thinkit.bigdata.core.entity.ResultMsg;
import com.thinkit.bigdata.core.util.PropsUtil;
import com.thinkit.bigdata.core.util.StringUtil;
import com.thinkit.bigdata.core.util.ValidateCodeUtil;
import com.thinkit.bigdata.core.util.httpUtil.HttpUtil;
import com.thinkit.bigdata.web.coremet.SystemStatic;
import com.thinkit.bigdata.web.model.config.*;
import com.thinkit.bigdata.web.model.sec.User;
import com.thinkit.bigdata.web.model.sys.SysConfig;
import com.thinkit.bigdata.web.service.config.AreaService;
import com.thinkit.bigdata.web.service.config.StatusAttService;
import com.thinkit.bigdata.web.service.sys.SysConfigService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 公共视图控制器
 *
 * @author starzou
 * @since 2014年4月15日 下午4:16:34
 **/
@Controller
public class CommonController {

    @Resource
    private AreaService areaService;

    @Resource
    private SysConfigService sysConfigService;

    @Resource
    private StatusAttService statusAttService;

    /**
     * @param request
     * @return
     */
    @RequestMapping("index")
    public String index(HttpServletRequest request, Model model) {
        User user = (User) request.getSession().getAttribute("userInfo");
        model.addAttribute("id", user.getId());
        model.addAttribute("name", user.getUsername());
        model.addAttribute("pwd", user.getPassword());
        return "index";
    }

    /**
     * 获取所有省份信息 不鉴权
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/common/reloadConfig")
    public ResultMsg reloadConfig() {
        StringBuilder sb = new StringBuilder();
        Map<String, Map<String, String>> ftpMap = (Map)PropsUtil.readJsonConfigToMap("ftp.json");
        if(ftpMap == null){
            sb.append("ftp.json读取异常");
        }else{
            SystemStatic.FTP_CONFIG_MAP = ftpMap;
        }
        Map<String, Object> provinceCitysMap = PropsUtil.readJsonConfigToMap("province-citys.json");
        if(provinceCitysMap == null){
            sb.append("province-citys.json读取异常");
        }else{
            SystemStatic.PROVINCE_CITY_MAP = provinceCitysMap;
        }
        if(sb.length()>0){
            return ResultMsg.errorResult(sb.toString());
        }else{
            return ResultMsg.successResult();
        }
    }

    /**
     * 获取所有省份信息 不鉴权
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/common/getAllArea")
    public ProvinceBean getAllArea() {
        List<SysAreaDto> list = areaService.selectAllArea();
        return new ProvinceBean(list);
    }

    /**
     * 根据主键获取系统配置信息
     *
     * @param code
     * @return
     */
    @ResponseBody
    @RequestMapping("/common/getSysConfigGetByCode")
    public Map<String,Object> sysConfigGetByPK(@RequestParam("code") String code) {
        SysConfig sysConfig = sysConfigService.sysConfigGetByPK(code);
        Map<String,Object> rsMap = new HashMap<>(2);
        rsMap.put("code",code);
        if(sysConfig!=null&&sysConfig.getValue()!=null){
            rsMap.put("value",sysConfig.getValue());
        }else{
            rsMap.put("value","");
        }
        return rsMap;
    }

    /**
     * 根据状态属性标识获取状态属性
     * @param pmsMap 参数
     * @return
     */
    @ResponseBody
    @RequestMapping("/common/getStatusAtt")
    public ResultMsg getStatusAtt(@RequestBody Map<String, Object> pmsMap) {
        String paramName = "type";
        if(pmsMap == null || pmsMap.get(paramName) == null){
            return ResultMsg.errorResult("参数为空");
        }
        String type = pmsMap.get(paramName).toString();
        SysStatusAttExample example = new SysStatusAttExample();
        if (StringUtil.isNotEmpty(type)) {
            example.createCriteria().andTypeEqualTo(type);
        }
        List<SysStatusAtt> atts = statusAttService.selectByExample(example);
        List<Map<String,Object>> list = new ArrayList<>();
        for(SysStatusAtt sysStatusAtt:atts){
            Map<String,Object> map = new HashMap<>(2);
            map.put("value",sysStatusAtt.getValue());
            map.put("name",sysStatusAtt.getName());
            list.add(map);
        }
        return ResultMsg.successResult(list);
    }

    /**
     * 根据主键获取系统配置信息
     *
     * @param map
     * @return
     */
    @ResponseBody
    @RequestMapping("/common/getSysConfigByCode")
    public Map<String,Object> sysConfigGetByPK(@RequestBody Map<String, Object> map) {
        Map<String,Object> rsMap = new HashMap<>(2);
        if (null != map && null != map.get("code")) {
            String code = map.get("code").toString();
            SysConfig sysConfig = sysConfigService.sysConfigGetByPK(code);
            rsMap.put("code",code);
            if(sysConfig!=null&&sysConfig.getValue()!=null){
                rsMap.put("value",sysConfig.getValue());
            }else{
                rsMap.put("value","");
            }
        }
        return rsMap;
    }

    /**
     * 根据主键获取系统配置信息
     * @param code
     * @return
     */
    @ResponseBody
    @RequestMapping("/common/getSysConfig/{code}")
    public String getSysConfigByPK(@PathVariable("code") String code) {
        SysConfig sysConfig = sysConfigService.sysConfigGetByPK(code);
        if(sysConfig!=null){
            return sysConfig.getValue();
        }
        return "";
    }

    /**
     * 获取省市信息
     * @param pmMap
     *  参数provinceCode 省份编码（空：所有接通省份，all：所有省份，具体code，所有该省下的地市数据）
     * @return
     *  rtnCode 0正常 1异常
     *  rtnMsg 消息
     *  data 数据
     */
    @ResponseBody
    @RequestMapping("/common/getProvinceCity")
    public ResultMsg getProvinceCity(@RequestBody Map<String, Object> pmMap) {
        ResultMsg resultMsg;
        try {
            Map<String,Object> maps = SystemStatic.PROVINCE_CITY_MAP;
            //all:所有省市  没有配置:权限省市  其他:地市
            Object provinceCode = pmMap.get("provinceCode");
            //1:5G   2:5GALL  其他默认0
            Object flagPm = pmMap.get("flag");
            int flag = (flagPm != null&&"1".equals(flagPm.toString()))?1:
                    (flagPm != null&&"2".equals(flagPm.toString()))?2:0;
            Map<String,Object> maps5G = (Map<String,Object>)maps.get("5G");
            if(flag==1&&(maps5G==null||maps5G.size()==0)){
                return ResultMsg.errorResult("没有配置5G重点城市");
            }
            Set<String> p5G = maps5G.keySet();
            Map<String,Object> mapsAll5G = (Map<String,Object>)maps.get("5G-ALL");
            if(flag==2&&(mapsAll5G==null||mapsAll5G.size()==0)){
                return ResultMsg.errorResult("没有配置5G全部城市");
            }
            Set<String> pAll5G = mapsAll5G.keySet();
            if (provinceCode == null || StringUtil.isEmpty(provinceCode.toString())) {
                Map<String,Object> dataMap = new HashMap(34);
                List<SysAreaDto> list;
                SysArea area = (SysArea) SecurityUtils.getSubject().getSession().getAttribute("areaInfo");
                if(area!=null){
                    SysAreaDto areaDto = new SysAreaDto();
                    areaDto.setCode(area.getCode());
                    areaDto.setArea(area.getArea());
                    list = new ArrayList<>();
                    list.add(areaDto);
                }else{
                    list = areaService.selectAllArea();
                }
                if(flag==1){
                    list.removeIf(areaDto -> !p5G.contains(areaDto.getCode()));
                }else if(flag==2){
                    list.removeIf(areaDto -> !pAll5G.contains(areaDto.getCode()));
                }
                if(list.size()==0){
                    return ResultMsg.errorResult("没有配置5G");
                }
                List<SysAreaDto> agList = new ArrayList<>();
                List<SysAreaDto> hkList = new ArrayList<>();
                List<SysAreaDto> lsList = new ArrayList<>();
                List<SysAreaDto> tzList = new ArrayList<>();
                for(SysAreaDto sysAreaDto:list ){
                    String code = sysAreaDto.getCode();
                    char c = code.charAt(0);
                    if((c>='a' && c<= 'g')||( c>='A' && c<='G')){
                        agList.add(sysAreaDto);
                    }else if((c>='h' && c<= 'k')||( c>='H' && c<='K')){
                        hkList.add(sysAreaDto);
                    }else if((c>='l' && c<= 's')||( c>='L' && c<='S')){
                        lsList.add(sysAreaDto);
                    }else if((c>='t' && c<= 'z')||( c>='T' && c<='Z')){
                        tzList.add(sysAreaDto);
                    }
                    dataMap.put(code,flag==1?maps5G.get(code):flag==2?mapsAll5G.get(code):maps.get(code));
                }
                Map<String,Object> provinceMaps = new LinkedHashMap<>(4);
                if(agList.size()>0){
                    provinceMaps.put("A-G",agList);
                }
                if(hkList.size()>0){
                    provinceMaps.put("H-K",hkList);
                }
                if(lsList.size()>0){
                    provinceMaps.put("L-S",lsList);
                }
                if(tzList.size()>0){
                    provinceMaps.put("T-Z",tzList);
                }
                dataMap.put("provinces",provinceMaps);
                resultMsg = ResultMsg.successResult(dataMap);
            } else if ("all".equals(provinceCode)) {
                Map<String,Object> dataMap = new LinkedHashMap(34);
                Map<String,Object> psMap = (Map<String,Object>)dataMap.get("provinces");
                List<String> toDelTags = new ArrayList();
                for(String pTag:psMap.keySet()){
                    List<SysAreaDto> agList = (List<SysAreaDto>)psMap.get(pTag);
                    if(flag==1){
                        agList.removeIf(areaDto -> !p5G.contains(areaDto.getCode()));
                    }else if(flag==2){
                        agList.removeIf(areaDto -> !pAll5G.contains(areaDto.getCode()));
                    }
                    if(agList.size()==0){
                        toDelTags.add(pTag);
                        continue;
                    }
                    for(SysAreaDto sysAreaDto:agList ){
                        String code = sysAreaDto.getCode();
                        dataMap.put(code,flag==1?maps5G.get(code):flag==2?mapsAll5G.get(code):maps.get(code));
                    }
                }
                for(String toDel:toDelTags){
                    psMap.remove(toDel);
                }
                dataMap.put("provinces",psMap);
                resultMsg = ResultMsg.successResult(dataMap);
            } else {
                Object o = flag==1?maps5G.get(provinceCode):flag==2?
                        mapsAll5G.get(provinceCode):maps.get(provinceCode);
                if(o==null){
                    resultMsg = ResultMsg.errorResult("该省没有配置相关信息");
                }
                else{
                    resultMsg = ResultMsg.successResult(o);
                }
            }
        } catch (Exception e) {
            resultMsg = ResultMsg.errorResult(1,"解析异常");
        }
        return resultMsg;
    }

    /**
     * 登录时 获取图片验证码
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/common/getValidateCode", method = RequestMethod.GET)
    public String getValidateCode(){
        // 调用工具类生成base64图片码
        ValidateCodeUtil.Validate validate = ValidateCodeUtil.genImgCode();
        // session中存入对应的图片验证码的值
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("loginImgCode", validate.getValue());
        return validate.getBase64Str();
    }

    @ResponseBody
    @RequestMapping(value = "/common/redirect", method = RequestMethod.POST)
    public ResultMsg redirect(@RequestBody Map<String, Object> pmMap) {
        if(pmMap==null){
            return ResultMsg.errorResult("参数为空");
        }
        Object addressPort_ = pmMap.get("addressPort");
        Object url_ = pmMap.get("url");
        Object params_ = pmMap.get("params");
        String addressPort = addressPort_ == null?"localhost:18080":addressPort_.toString();
        String url = url_==null?"/":url_.toString();
        String response;
        try {
            response = HttpUtil.sendJsonHttpPost(
                    StringUtils.join("http://",addressPort,url),
                    JSON.toJSONString(params_));
        }catch (Exception e){
            return ResultMsg.errorResult("系统异常");
        }
        try {
            return ResultMsg.successResult(JSON.parse(response));
        }catch (Exception e){
            return ResultMsg.successResult(response,"");
        }
    }
}